package fx.stage;

import cn.hutool.core.thread.NamedThreadFactory;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import fx.TransparentForm;
import fx.util.ListenerUtil;
import fx.util.StockGetThreadUtil;
import javafx.application.Platform;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class StockShow {

    public Stage getShowStage() throws IOException, AWTException {
        Stage primaryStage = new Stage();
        // 设置背景透明
        primaryStage.initStyle(StageStyle.TRANSPARENT);
        // 设置桌面图标
        primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/img/sea.gif")));

        Scene scene = getScene(primaryStage);
        primaryStage.setScene(scene);
        // 窗体始终悬浮在最顶
        primaryStage.setAlwaysOnTop(true);
        // 设置窗口的初始位置
        Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();
        primaryStage.setX(primaryScreenBounds.getWidth() - 150);
        primaryStage.setY(primaryScreenBounds.getHeight() - 70);

        // 构建托盘图标
        this.buildTray(primaryStage);
        return primaryStage;
    }

    private Scene getScene(Stage primaryStage) {

        VBox box = new VBox();
        box.setStyle("-fx-background:transparent;");
        int width = 125;
        int height = TransparentForm.stock.size() * 25;
        Scene scene = new Scene(box, width, height);
        scene.setFill(new Color(0f, 0f, 0f, 0.01f));

        // 拖动监听器
        ListenerUtil.addDragListener(primaryStage, box);
        // 鼠标滚轮事件
        ListenerUtil.addMouseWheel(primaryStage, box);
        // 定时刷新
        for (String code : TransparentForm.stock.keySet()) {
            Text text = new Text();
            text.setFont(new Font(20));
            text.setFill(Color.RED);
            StockGetThreadUtil.submitGetDateJob(() -> Platform.runLater(() -> {
                currentPrice(text, code);
            }));
            box.getChildren().add(text);
        }
        return scene;
    }

    /**
     * 构建托盘图标
     *
     * @param primaryStage 主画布
     */
    private void buildTray(Stage primaryStage) throws IOException, AWTException {
        //构建系统托盘图标
        BufferedImage image = ImageIO.read(Objects.requireNonNull(getClass().getResourceAsStream("/img/sea.png")));
        final TrayIcon trayIcon = new TrayIcon(image, "中远海控");
        trayIcon.setImageAutoSize(true);
        //获取系统托盘
        final SystemTray tray = SystemTray.getSystemTray();
        //添加鼠标点击事件
        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                //双击左键
                if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
                    Platform.runLater(() -> {
                        if (primaryStage.isIconified()) {
                            primaryStage.setIconified(false);
                        }
                        if (!primaryStage.isShowing()) {
                            primaryStage.show();
                        }
                        primaryStage.toFront();
                    });
                }
                //鼠标右键,关闭应用
                else if (e.getButton() == MouseEvent.BUTTON3) {
                    Platform.setImplicitExit(true);
                    tray.remove(trayIcon);
                    StockGetThreadUtil.close();
                    Platform.runLater(primaryStage::close);
                    Platform.exit();
                }
            }
        });
        //添加托盘图标
        tray.add(trayIcon);
    }


    private void currentPrice(Text text, String code) {

        String result = HttpUtil.get("http://hq.sinajs.cn/list=sh" + code, CharsetUtil.CHARSET_UTF_8);
        String[] detail = result.split(",");
        float ratio = (Float.parseFloat(detail[3]) - Float.parseFloat(detail[2])) / Float.parseFloat(detail[2]) * 100;
        text.setText(detail[3] + "(" + String.format("%.2f", ratio) + ")");
        if (ratio < 0) {
            if (text.getFill() != Color.GREEN) {
                text.setFill(Color.GREEN);
            }
        } else {
            if (text.getFill() != Color.RED) {
                text.setFill(Color.RED);
            }
        }
    }
}
